import 'dart:io';

import 'package:pacsun/utils/share_platform.dart';
import 'package:logger/logger.dart';
import 'package:url_launcher/url_launcher.dart';

class ShareUtils {
  static final logger = Logger();

  /// 分享图片到ins 发布页面
  static Future<void> shareImageToInstagram(String path) async {
    if (!await isInstagramInstalled()) {
      logger.e("设备没有安装 ins app");
    }
    final uri = Uri.parse('instagram://library?AssetPath=$path');
    if (await _canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      await _openAppStore(SharePlatform.instagram);
    }
  }

  /// 分享视频到ins 发布页面
  static Future<void> shareVideoToInstagram(String path) async {
    final uri = Uri.parse('instagram://library?LocalIdentifier=$path');
    if (await _canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      await _openAppStore(SharePlatform.instagram);
    }
  }

  ///监测是否安装 ins App
  static Future<bool> isInstagramInstalled() async {
    return await canLaunchUrl(Uri.parse('instagram://app'));
  }

  /// 检测是否安装 youtube app
  static Future<bool> isYoutubeInstalled() async {
    return await canLaunchUrl(Uri.parse('vnd.youtube://'));
  }

  static Future<bool> _canLaunchUrl(Uri uri) async {
    try {
      return await canLaunchUrl(uri);
    } catch (e) {
      logger.w("无效的URL:$e");
      return false;
    }
  }

  /// 分享图片到youtube
  static Future<void> shareImageToYoutube(String path) async {
    if (!await isYoutubeInstalled()) {
      logger.e("设备没有安装 ins app");
    }
    final uri = Uri.parse('vnd.youtube://upload?file=$path');
    if (await _canLaunchUrl(uri)) {
      await launchUrl(
        uri,
        mode: LaunchMode.externalApplication,
      );
    } else {
      await _openAppStore(SharePlatform.youTube);
    }
  }

  /// 分享视频到youtube
  static Future<void> shareVideoToYoutube(String path) async {
    final uri = Uri.parse('https://www.youtube.com/upload?video=$path');
    if (await _canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      await _openAppStore(SharePlatform.youTube);
    }
  }

  static Future<void> _openAppStore(SharePlatform platform) async {
    final storeUrl = platform == SharePlatform.instagram
        ? Platform.isIOS
            ? 'https://apps.apple.com/app/instagram/id389801252'
            : 'https://play.google.com/store/apps/details?id=com.instagram.android'
        : Platform.isIOS
            ? 'https://apps.apple.com/app/youtube/id544007664'
            : 'https://play.google.com/store/apps/details?id=com.google.android.youtube';

    final Uri uri = Uri.parse(storeUrl);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      throw Exception('Could not launch app store');
    }
  }
}
